//
//  wangjimimaViewController.m
//  YeDian
//
//  Created by 罗西 on 4/6/16.
//  Copyright © 2016 罗西. All rights reserved.
//

#import "wangjimimaViewController.h"
#import "ASIFormDataRequest.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "Toast+UIView.h"
#import "Tools.h"
#import "ConfigData.h"
#import "JSON.h"
#import "THud.h"

@interface wangjimimaViewController (){
    NSString *Vcode;
}

@property(nonatomic,strong)NSDictionary* dic;

@end

@implementation wangjimimaViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"忘记密码";
    
    CGRect frame_img= CGRectMake(0,(44-19)/2,19,19);
    UIImageView* backView=[[UIImageView alloc] initWithFrame:frame_img];
    backView.image=[UIImage imageNamed:@"back2016"];
    CGRect frameBtn= CGRectMake(0, 0,50, 44);
    UIButton* homeBtn= [[UIButton alloc] initWithFrame:frameBtn];
    [homeBtn addTarget:self action:@selector(backFn) forControlEvents:UIControlEventTouchUpInside];
    [homeBtn addSubview:backView];
    UIBarButtonItem* barHomeBtn= [[UIBarButtonItem alloc] initWithCustomView:homeBtn];
    self.navigationItem.leftBarButtonItem=barHomeBtn;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self loadUI];
}

-(void)backFn{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)loadUI{
    NSArray *array = @[@"请输入您的手机号码",@"请输入您的密码",@"请确认您的密码",@"请输入验证码"];
    
    for (int i = 0; i < array.count; i++) {
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 50+(40)*i, SCREEN_WIDTH-80 , 30)];
        bgView.backgroundColor = [UIColor whiteColor];
        bgView.layer.cornerRadius = 15;
        bgView.layer.borderWidth = 1.0f;
        bgView.layer.borderColor = [UIColor colorWithRed:235/255.0 green:93/255.0 blue:94/255.0 alpha:1.0].CGColor;
        bgView.tag = 200+i;
        [self.view addSubview:bgView];
        bgView.center = CGPointMake(SCREEN_WIDTH/2, bgView.center.y);
        
        UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(20, 2.5, SCREEN_WIDTH-80-40, 25)];
        textField.placeholder = [array objectAtIndex:i];
        textField.tag = 500+i;
        //[textField setValue:[UIColor blackColor] forKeyPath:@"_placeholderLabel.textColor"];
        textField.font = [UIFont systemFontOfSize:13];
        [bgView addSubview:textField];
        
        if (i == 0) {
            textField.keyboardType = UIKeyboardTypePhonePad;
        }else if (i == 1 || i == 2){
            textField.secureTextEntry = YES;
        }else if (i == 3){
            textField.keyboardType = UIKeyboardTypeNumberPad;
        }
        
        if (i == array.count-1) {
            textField.frame = CGRectMake(20, 2.5, (SCREEN_WIDTH-80)*2/3-30, 25);
            
            UIView *sepView = [[UIView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-80)*2/3, 2.5, 1, 25)];
            sepView.backgroundColor = [UIColor colorWithRed:235/255.0 green:93/255.0 blue:94/255.0 alpha:1.0];
            [bgView addSubview:sepView];
            
            UIButton *yanzhengBtn = [[UIButton alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-80)*2/3, 2.5, (SCREEN_WIDTH-80)*1/3, 25)];
            [yanzhengBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
            yanzhengBtn.titleLabel.textAlignment = NSTextAlignmentRight;
            yanzhengBtn.titleLabel.font = [UIFont systemFontOfSize:13];
            [yanzhengBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [yanzhengBtn setBackgroundColor:[UIColor clearColor]];
            [bgView addSubview:yanzhengBtn];
            yanzhengBtn.tag = 999;
            [yanzhengBtn addTarget:self action:@selector(getVcode) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    
    UIButton *okBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 210+40, SCREEN_WIDTH-80, 30)];
    [okBtn addTarget:self action:@selector(btnClickEvent5) forControlEvents:UIControlEventTouchUpInside];
    okBtn.tag = 401;
    okBtn.backgroundColor = [UIColor colorWithRed:235/255.0 green:93/255.0 blue:94/255.0 alpha:1.0];
    [okBtn setTitle:@"修改密码" forState:UIControlStateNormal];;
    //[okBtn setTitleColor:[UIColor colorWithRed:235/255.0 green:93/255.0 blue:94/255.0 alpha:1.0] forState:UIControlStateNormal];
    okBtn.layer.cornerRadius = 15;
    [self.view addSubview:okBtn];
    okBtn.center = CGPointMake(SCREEN_WIDTH/2, okBtn.center.y);
}

//注册
-(void)btnClickEvent5{
    UITextField *tf1 = [self.view viewWithTag:500];
    UITextField *tf2 = [self.view viewWithTag:501];
    UITextField *tf3 = [self.view viewWithTag:502];
    UITextField *tf4 = [self.view viewWithTag:503];
    
    if (![self checkTel:tf1.text]) {
        
    }else if (tf2.text.length == 0){
        [self.view makeToast:@"请输入密码" duration:1.0 position:@"center"];
    }else if (![tf3.text isEqualToString:tf2.text]){
        [self.view makeToast:@"确认密码应与输入密码相同" duration:1.0 position:@"center"];
    }else if (tf4.text.length == 0){
        [self.view makeToast:@"请输入验证码" duration:1.0 position:@"center"];
    }else if (![tf4.text isEqualToString:Vcode]){
        [self.view makeToast:@"验证码不正确" duration:1.0 position:@"center"];
    }
    else{
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [[MBProgressHUD showHUDAddedTo:app.window animated:YES] setLabelText:@"加载中,请稍后..."];
        
        [NSThread detachNewThreadSelector:@selector(doReg) toTarget:self withObject:nil];
    }
}

-(void)doReg{
    UITextField *tf1 = [self.view viewWithTag:500];
    UITextField *tf2 = [self.view viewWithTag:501];
    UITextField *tf4 = [self.view viewWithTag:503];
    
    NSString * m = tf1.text;
    NSString * p = tf2.text;
    NSString * c = tf4.text;
    
    NSString* loginURL=HOST;
    loginURL=[loginURL stringByAppendingString:@"/index.php/appUser/updatePwdFn"];
    
    
    
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    
    
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    
    
    [req addPostValue:m forKey:@"mp"];
    [req addPostValue:p forKey:@"pwd"];
    
    
    
    
    
    [req startSynchronous];
    NSError *error = [req error];
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        NSString *response = [req responseString];
        
        
        self.dic=[NSMutableDictionary dictionaryWithDictionary:[response JSONValue]];
        NSLog(@"注册结果..%@",self.dic);
        
        if ([[self.dic objectForKey:@"code"]intValue] == 1) {
//            UIAlertView * successTip = [[UIAlertView alloc] initWithTitle:@"信息提示:" message:@"修改密码成功，请重新登录！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//            [self.view addSubview:successTip];
//            [successTip show];
            
            dispatch_sync(dispatch_get_main_queue(), ^{
                //Update UI in UI thread here
                UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"信息提示" message:@"修改密码成功，请重新登录！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alert show];
            });

            //[[THud sharedInstance]showText:@"修改成功!请重新登录!" Delay:1.0];
             [self.navigationController popViewControllerAnimated:YES];
        }else{
//            UIAlertView * successTip = [[UIAlertView alloc] initWithTitle:@"信息提示:" message:@"注册失败！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//            [successTip show];
            [[THud sharedInstance]showText:@"修改失败"];
        }
    }

    
    
}

-(void)closeLoginPage{
   
}

-(void)getVcode{
    [self.view endEditing:YES];
    UITextField *tf1 = [self.view viewWithTag:500];
    if (![self checkTel:tf1.text]) {
        return;
    }
    int i = arc4random() % 10000 + 10000;
    Vcode = [NSString stringWithFormat:@"%d",i];
    Vcode = [Vcode stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@""];
    //    [req addPostValue:tf1.text forKey:@"mobile"];
    //    [req addPostValue:[NSString stringWithFormat:@"%@",Vcode] forKey:@"msg"];
    //    [req addPostValue:@"1" forKey:@"needstatus"];
    
    NSString* loginURL=[NSString stringWithFormat:@"%@/sms.php?mp=%@&code=%@",HOST,tf1.text,[NSString stringWithFormat:@"%@",Vcode]];
    loginURL=[loginURL stringByAppendingString:@""];
    
    
    
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    
    
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    
    
    
    
    NSLog(@"req:%@",req.url);
    
    [req startSynchronous];
    NSError *error = [req error];
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        NSString *response = [req responseString];
        NSLog(@"返回结果..%@",response);
        [self.view makeToast:@"获取验证码成功" duration:1.0 position:@"center"];
        self.dic=[NSMutableDictionary dictionaryWithDictionary:[response JSONValue]];
        NSLog(@"注册结果..%@",self.dic);
        
    }
    
    
    UIButton *btn = [self.view viewWithTag:999];
    __block int timeout=59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [btn setTitle:@"获取验证码" forState:UIControlStateNormal];
                btn.userInteractionEnabled = YES;
                
                
            });
        }else{
            //            int minutes = timeout / 60;
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [btn setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime] forState:UIControlStateNormal];
                btn.userInteractionEnabled = NO;
                
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
}

- (BOOL)checkTel:(NSString *)str
{
    if ([str length] == 0) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"手机号不能为空" message:@"请输入11位有效手机号" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }
    NSString *regex = @"^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:str];
    if (!isMatch) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入正确的手机号码" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }
    return YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
